<?php

namespace Icsoc\DataBundle\Model;

use Guzzle\Http\Exception\ClientErrorResponseException;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Guzzle\Http\Client;

/**
 * 生成下载文件
 *
 * @package Icsoc\DataBundle\Model
 */
class ExportModel extends BaseModel
{
    /** @var \Doctrine\DBAL\Connection */
    private $conn;
    private $logger;
    /**
     * $allType 用来解决部分字段格式问题，目前只添加了自动转换成时间格式,和枚举
     * @var array
     */
    private  $allType = array(
        'excel' => array(
            'datetime' => array(
                'formaters' => array(
                    array(
                        'formater' => 'datetime',
                        'format' => '%Y-%m-%d %H:%M:%S',
                    ),
                ),
            ),
            'second' => array(
                'formaters' => array(
                    array(
                        'formater' => 'second',
                    ),
                ),
            )
        ),
        'csv' => array(
            'datetime' => array(
                'formaters' => array(
                    array(
                    'formater' => 'datetime',
                    'format' => '%Y-%m-%d %H:%M:%S',
                    ),
                ),
            ),
            'second' => array(
                'formaters' => array(
                    array(
                        'formater' => 'second',
                    ),
                ),
            )
        ),
    );

    /**
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->conn = $this->container->get('doctrine.dbal.default_connection');
        $this->logger = $this->container->get('logger');
    }

    /**
     * @param string $query
     * @param array $params
     * @return mixed
     */
    public function interpolateQuery($query, $params)
    {
        $keys = array();
        foreach ($params as $key => $value) {
            if (is_string($key)) {
                $keys[] = '/:'.$key.'/';
            } else {
                $keys[] = '/[?]/';
            }
            $params[$key] = "'".$value."'";
        }

        $query = preg_replace($keys, $params, $query, 1, $count);

        return $query;
    }

    /**
     * 老的异步导出
     * 明细报表专用
     * 处理原来的数组，方便创建任务
     * $data //所有的字段   array('time' => 'Time')
     * $exprot //需要导出的格式   csv/excel
     * $type = array(
            'start_time' => 'datetime',
            'endresult' => 'enum',
            '字段名称' => '要转换的格式 datetime 是时间格式',
        );
     * $endResults  //需要转换时间格式之外的格式时，用到这个变量
     * @param array $data
     * @param string $export
     * @param array $type
     * @param array $endResults
     * @return array
     */
    public function getOldNewTitle($oldData, $export = '', $type = '', $endResults = '')
    {
        $data = array();
        foreach ($oldData as $key => $val) {
            $data[$key] = $val['title'];
        }
        if (!empty($endResults['enum'])) {
            $results = array();
            foreach ($endResults['enum'] as $key => $val) {
                $results['enum'][$key] = array(
                    'formaters' => array(
                        array(
                            'formater' => 'enum',
                            'enum' => $val,
                        ),
                    ),
                );
            }

            $this->allType[$export]['enum'] = $results['enum'];
        }
        $keys = 0;
        $title = array();
        $translator = $this->container->get('translator');
        if (!empty($export) && !empty($type)) {
            foreach ($data as $key => $val) {
                $title[$keys] = array(
                    'field' => $key,
                    'name' => $translator->trans($val),
                );
                //ge
                if ($key == 'caller_areacode') {
                    $title[$keys]['cell_type'] = 'string';
                };
                foreach ($type as $k => $v) {
                    if ($k == $key && $v == 'datetime') {
                        $title[$keys] = array_merge($title[$keys], $this->allType[$export][$v]);
                    } else if ($k == $key && $v == 'second') {
                        $title[$keys] = array_merge($title[$keys], $this->allType[$export][$v]);
                    } else if($k == $key && $v != 'datetime' && $v != 'second') {
                        $title[$keys] = array_merge($title[$keys], $this->allType[$export][$v][$k]);
                    }
                }
                $keys += 1;
            }
        } else {
            foreach ($data as $key => $val) {
                $title[$keys] = array(
                    'field' => $key,
                    'name' => $translator->trans($val),
                );
                $keys += 1;
            }
        }

        return $title;
    }

    /**
     * 新的异步导出处理col
     * 明细报表专用
     * 处理原来的数组，方便创建任务
     * @param array $title
     * @param array $type
     * @param array $endResults
     * @return array
     */
    public function getNewTitle($title, $type = '', $endResults = '')
    {
        $translator = $this->container->get('translator');
        foreach ($type as $key => $val) {
            if (!is_array($val)) {
                if (empty($endResults[$type[$key]][$key])) {
                    $title[$key]['filters'] = array(
                        array(
                            'filter' => $val,
                        ),
                    );
                } else {
                    $title[$key]['filters'] = array(
                        array(
                            'filter' => $val,
                            $val => $endResults[$type[$key]][$key],
                        ),
                    );
                }
            } else {
                foreach ($val as $ke => $vl) {
                    if (empty($endResults[$ke][$key])) {
                        $title[$key]['filters'] = array(
                            array(
                                'filter' => $ke,
                            ),
                        );
                    } else {
                        $b = array();
                        foreach ($vl as $v) {
                            if (!empty($endResults[$ke][$key][$v])) {
                                $a = $endResults[$ke][$key][$v];
                                unset($endResults[$ke][$key][$v]);
                                $b['filter'] = $ke;
                                $b[$ke] = $endResults[$ke][$key];
                                $b[$v] = $a;
                            }
                        }
                        $title[$key]['filters'] = array(
                            $b,
                        );
                    }
                }
            }
        }
        foreach ($title as $k => $v) {
            if (empty($v['title'])) {
                continue;
            }
            $title[$k]['title'] = $translator->trans($v['title']);
        }

        return $title;
    }

    /**
     * 新版异步导出
     * 创建下载任务并存储到数据库
     * @param string $export
     * @param array $data
     * @param string $name
     * @return array
     */
    public function newRecord($export, $data, $name)
    {
        $url = $this->container->getParameter('new_create_download_file_url');
        $user = $this->container->get("security.token_storage")->getToken()->getUser();
        $submitUser = $user->getId().'-'.$user->getLoginType();
        $client = new Client();

        $data['es_server'] = 1;
        $data['es_pk'] = 'id';
        $data['mongo_server'] = 1;
        $data['mongo_db'] = $this->container->getParameter('mongodb')['database'];
        $data['mongo_pk'] = '_id';

        switch ($export) {
            case 'csv':
                $data['filetype'] = 2;
                break;
            case 'excel':
                $data['filetype'] = 1;
                break;
            default:
                exit;
        }
        try {
            $res = $client->post($url, null, $data);
            $token = $res->send()->json();
            $this->logger->info(sprintf("异步导出创建文件token_id【%s】,【%s】", $token['result']['token_id'], json_encode($data)));
        } catch (\Exception $e) {
            return array('code'=>401, 'message'=>'添加下载任务失败');
        }
        if (empty($token['result']['token_id'])) {
            return array('code' => 402, 'message' => '添加下载任务失败');
        }

        $addData['token_id'] = $token['result']['token_id'];
        $addData['progress'] = empty($token['result']['progress']) ? 0 : floor($token['result']['progress']*100);
        $addData['download_url'] = empty($token['result']['url']) ? '' : $token['result']['url'];
        $addData['submit_time'] = empty($token['result']['createdtime']) ? time() : $token['result']['createdtime'];
        $addData['submit_user'] = $submitUser;
        $time = date("YmdHis", $addData['submit_time']);
        $addData['name'] = $name.$time.$export;
        $addData['datacount'] = $token['result']['datacount'];
        $addData['export_version'] = 2;   //2为新版导出

        try {
            $this->conn->insert('win_download_log', $addData);
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());

            return array('code'=>403, 'message'=>'添加下载任务失败');
        }

        return array('code'=>200, 'message'=>'成功添加下载任务');
    }

    /**
     * 老版异步导出
     * 创建下载任务并存储到数据库
     * @param string $export
     * @param array $data
     * @param string $name
     * @return array
     */
    public function record($export, $data, $name)
    {
        $url = $this->container->getParameter('create_download_file_url');
        $user = $this->container->get("security.token_storage")->getToken()->getUser();
        $submitUser = $user->getId().'-'.$user->getLoginType();
        $client = new Client();
        $data['datasource'] = 1;
        switch ($export) {
            case 'csv':
                $data['filetype'] = 2;
                break;
            case 'excel':
                $data['filetype'] = 1;
                break;
            default:
                exit;
        }
        try {
            $res = $client->post($url, null, $data);
            $token = $res->send()->json();
        } catch (\Exception $e) {
            return array('code'=>401, 'message'=>'添加下载任务失败');
        }
        if (empty($token['result']['token_id'])) {
            return array('code' => 402, 'message' => '添加下载任务失败');
        }

        $addData['token_id'] = $token['result']['token_id'];
        $addData['progress'] = empty($token['result']['progress']) ? 0 : floor($token['result']['progress']*100);
        $addData['download_url'] = empty($token['result']['url']) ? '' : $token['result']['url'];
        $addData['submit_time'] = empty($token['result']['createdtime']) ? time() : $token['result']['createdtime'];
        $addData['submit_user'] = $submitUser;
        $time = date("YmdHis", $addData['submit_time']);
        $addData['name'] = $name.$time.$export;
        $addData['datacount'] = $token['result']['datacount'];

        try {
            $this->conn->insert('win_download_log', $addData);
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());

            return array('code'=>403, 'message'=>'添加下载任务失败');
        }

        return array('code'=>200, 'message'=>'成功添加下载任务');
    }
}
